<template>
	<u-upload 
	ref = "upload"
	:action="action"
	:max-size="5 * 1024 * 1024"
	 max-count="1"
	:before-upload="beforeUpload"
	
	:custom-btn="true"
	:show-progress="false"	
	:form-data="formData"
	:multiple="false"
	:deletable="false"	
	:show-upload-list="true"
	width="0"
	height="0"
	@on-success="onSuccess"	
								>
		<u-avatar slot="addBtn" :src="vuex_user.avatar_url" size="140"></u-avatar>
	 </u-upload>
</template>

<script>
	let _this ={}
	export default {
		name:"oss-upload",
		data() {
			return {
				action:'',
				formData:{},
				upFileName:''
			};
		},
		created(){
			_this = this
		},
		methods:{
			/**
			 * 上传前的钩子
			 * 注意在小程序中 this 可能会丢失
			 */
			async beforeUpload(index,list){
			//	console.log(list)
				
				const{file} = list[0]
				// #ifdef H5
				const fileName = file.name
				// #endif
				
				// #ifndef H5
				const fileName = file.path
				// #endif
				console.log(fileName)
				
				//请求api ， 获取oss token
				const osstoken = await _this.$u.api.ossToken()
				console.log(osstoken)
				// 设置上传域名
				_this.action = osstoken.host
				console.log(_this.action)
				//处理唯一文件名
				const suffix = fileName.slice(fileName.lastIndexOf('.'))
				console.log(suffix)
				const upFileName = _this.$u.guid(20)+suffix
				console.log(upFileName)
				_this.upFileName = upFileName
				//额外的上传参数
				_this.formData={
					'key':upFileName,//上传的文件名
					'policy':osstoken.policy,
					'OSSAccessKeyId':osstoken.accessid,
					'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
					 'signature':osstoken.signature,
				}
					
				return true
			},
			 async onSuccess(){
				 // 移除预览区的图片
				 this.$refs.upload.remove(0)
				//请求api更新头像
				await this.$u.api.tx({avatar:this.upFileName}) 
				//更新缓存的用户信息
				this.$u.toast('更新成功')
				this.$u.utils.getUser()
				
			}
		}
	}
</script>

<style>

</style>
